package com.yugao.fintech.libra.auth.model;

import cn.hutool.core.util.StrUtil;
import com.yugao.fintech.libra.common.constants.UserCons;
import com.yugao.fintech.libra.common.enums.AuthErrorEnum;

import java.util.Objects;
import java.util.function.Function;

/**
 * 检查登录请求参数
 */
public class CheckLoginParam {
    private final String userName;
    private final String password;

    private AuthErrorEnum authErrorEnum;

    public static CheckLoginParam of(String userName, String password) {
        return new CheckLoginParam(userName, password);
    }


    public CheckLoginParam(String userName, String password) {
        this.userName = userName;
        this.password = password;
    }

    /**
     * 判断用户名或者密码是否为空
     */
    public CheckLoginParam isAnyEmpty() {
        if (Objects.isNull(this.authErrorEnum) && (StrUtil.isEmpty(userName) ||  StrUtil.isEmpty(password))) {
            this.authErrorEnum = AuthErrorEnum.USER_LOGIN_USERNAME_OR_PASSWORD_MISSING;
        }
        return this;
    }

    /**
     * 检查密码长度
     */
    public CheckLoginParam passwordLength() {
        // 密码如果不在指定范围内 错误
        if (Objects.isNull(this.authErrorEnum)
                && StrUtil.isNotEmpty(password)
                && ((password.length() < UserCons.Password.MIN_LENGTH)
                || (password.length() > UserCons.Password.MAX_LENGTH))) {
            this.authErrorEnum = AuthErrorEnum.USER_LOGIN_PASSWORD_OUT_OF_RANGE;
        }
        return this;
    }

    public CheckLoginParam userNameLength() {
        // 密码如果不在指定范围内 错误
        if (Objects.isNull(this.authErrorEnum) && (userName.length() < UserCons.UserName.MIN_LENGTH
                || userName.length() > UserCons.UserName.MAX_LENGTH)) {
            this.authErrorEnum = AuthErrorEnum.USER_LOGIN_USERNAME_OUT_OF_RANGE;
        }
        return this;
    }

    public void throwError(Function<AuthErrorEnum, RuntimeException> biConsumer) {
        if (Objects.nonNull(this.authErrorEnum)) {
            throw biConsumer.apply(this.authErrorEnum);
        }
    }
}
